package com.itmuch.cloud.microserviceconsumermovieribbonhystrix.controller;

import com.itmuch.cloud.microserviceconsumermovieribbonhystrix.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@Slf4j
public class MovieController {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private LoadBalancerClient loadBalancerClient;

    @GetMapping(value = "/user/{id}",produces = { "application/json;charset=UTF-8" })
    @HystrixCommand(fallbackMethod = "findByIdFallback")
    public User findById(@PathVariable Long id)
    {
        /*return restTemplate.getForObject("http://localhost:8000/"+id,User.class);*/
        return restTemplate.getForObject("http://microservice-provider-user/"+id,User.class);
    }

    public User findByIdFallback(Long id)
    {
        User user = new User();
        user.setId(-1L);
        user.setAge(0);
        user.setName("系统默认用户");
        user.setUsername("五天");
        return user;
    }

    @GetMapping("/log-instance")
    public void logUserInstance()
    {
        ServiceInstance serviceInstance = loadBalancerClient.choose("microservice-provider-user");
        //打印当前选择的是哪个节点
        log.info("{}:{}:{}",serviceInstance.getServiceId(),serviceInstance.getHost(),serviceInstance.getPort());
    }
}
